package com.ufo.store.management.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.database.MicrosoftSQLServerHelper;
import com.ufo.store.management.database.LocalDatabaseHelper;
import com.ufo.store.management.entity.Isszmbalv3BranchInfo;
import com.ufo.store.management.entity.Isszmbalv3Member;
import com.ufo.store.management.entity.Isszmbalv3PayFlow;
import com.ufo.store.management.entity.Isszmbalv3SaleDetailInfo;
import com.ufo.store.management.entity.Isszmbalv3StockInfo;
import com.ufo.store.management.entity.Isszmbalv3SupcustInfo;
import com.ufo.store.management.entity.Member;
import com.ufo.store.management.entity.PayMaster;
import com.ufo.store.management.entity.SaleDetailInfo;
import com.ufo.store.management.entity.StockInfo;
import com.ufo.store.management.common.Config;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.view.ObservableScrollView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import a_vcard.android.provider.Contacts;
import a_vcard.android.syncml.pim.vcard.ContactStruct;
import a_vcard.android.syncml.pim.vcard.VCardComposer;


/**
 * Created by Administrator on 2015/9/15 0015.
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {
    private String TAG = SettingActivity.class.getSimpleName();
    private SharedPreferences mSettings = null;
    private Switch mDisplayPictureSB = null;
    private Switch mDisplayInnerCircleSB = null;
    private Switch mDisplayCostSB = null;
    private Switch mDatabaseSB = null;
    private EditText mStoreNameEt = null;
    private EditText mDatabaseStatisticsStockNumberEt = null;
    private EditText mDatabaseSqlServerHostEt = null;
    private EditText mDatabaseSqlServerUserEt = null;
    private EditText mDatabaseSqlServerPasswordEt = null;
    private EditText mDatabaseSqlServerDatabaseNameEt = null;
    private EditText mSynchronousSourceDateEt = null;

    private TextView mFastfoodSynchronousTipsTv;
    private TextView mIsszmbalv3SynchronousTipsTv;
    private TextView mFastfoodMemberExportTipsTv;
    private TextView mIsszmbalv3MemberExportTipsTv;
    private TextView mVersionTv;

    private ObservableScrollView content_sv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        toolbar.setTitle("软件设置");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_back_selector);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initData() {
        mSettings = PreferenceManager.getDefaultSharedPreferences(BarApplication.getInstance());
    }

    private void initView() {
        setContentView(R.layout.activity_setting);
        findViewById(R.id.display_picture_rl).setOnClickListener(this);
        findViewById(R.id.display_cost_rl).setOnClickListener(this);
        findViewById(R.id.display_inner_circle_rl).setOnClickListener(this);
        findViewById(R.id.database_sqlserver_rl).setOnClickListener(this);
        //findViewById(R.id.database_sqlserver_host_rl).setOnClickListener(this);
        //findViewById(R.id.database_sqlserver_user_rl).setOnClickListener(this);
        //findViewById(R.id.database_sqlserver_password_rl).setOnClickListener(this);
        findViewById(R.id.database_fastfood_sqlserver_synchronous_rl).setOnClickListener(this);
        findViewById(R.id.database_isszmbalv3_sqlserver_synchronous_rl).setOnClickListener(this);
        findViewById(R.id.fastfood_member_export_rl).setOnClickListener(this);
        findViewById(R.id.isszmbalv3_member_export_rl).setOnClickListener(this);
        findViewById(R.id.database_local_delete_rl).setOnClickListener(this);
        findViewById(R.id.about_rl).setOnClickListener(this);

        content_sv = (ObservableScrollView) findViewById(R.id.content_sv);
        content_sv.setScrollViewListener(new ObservableScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
//                Log.i("debug", "y=" + y + " overlay.getWidth()=" + overlay.getWidth() + "   overlay.getHeight()=" + overlay.getHeight()
//                        + "  jiequHeight=" + (int) Utils.sp2px(getResources(), 72f));
            }
        });

        mVersionTv = (TextView) findViewById(R.id.version_tv);
        mVersionTv.setText("软件版本：" + Utils.getClientVersionName(this));
        mFastfoodSynchronousTipsTv = (TextView) findViewById(R.id.fastfood_synchronous_tips_tv);
        mIsszmbalv3SynchronousTipsTv = (TextView) findViewById(R.id.isszmbalv3_synchronous_tips_tv);
        mFastfoodMemberExportTipsTv = (TextView) findViewById(R.id.fastfood_export_tips_tv);
        mIsszmbalv3MemberExportTipsTv = (TextView) findViewById(R.id.isszmbalv3_export_tips_tv);

        mStoreNameEt = (EditText)findViewById(R.id.store_name_et);
        mStoreNameEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putString("store_name", s.toString());
                editor.commit();
                BarApplication.getInstance().mStoreName = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mDisplayCostSB = (Switch) findViewById(R.id.display_cost_s);
        mDisplayCostSB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putBoolean("display_cost", isChecked);
                editor.commit();
                BarApplication.getInstance().mbStockDisplayCost = isChecked;
            }
        });

        mDisplayPictureSB = (Switch) findViewById(R.id.display_picture_s);
        mDisplayPictureSB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putBoolean("display_picture", isChecked);
                editor.commit();
                BarApplication.getInstance().mbStockDisplayPicture = isChecked;
            }
        });


        mDisplayInnerCircleSB = (Switch) findViewById(R.id.display_inner_circle_s);
        mDisplayInnerCircleSB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putBoolean("display_inner_circle", isChecked);
                editor.commit();
                BarApplication.getInstance().mbStockDisplayInnerCircle = isChecked;
            }
        });

        mDatabaseSB = (Switch) findViewById(R.id.database_sqlserver_s);
        mDatabaseSB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putBoolean("database_sqlserver", isChecked);
                editor.commit();
                BarApplication.getInstance().mDatabaseIsSqlServer = isChecked;
                setView(isChecked);
            }
        });

        mDatabaseStatisticsStockNumberEt = (EditText) findViewById(R.id.database_statistics_stock_number_et);
        mDatabaseStatisticsStockNumberEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                SharedPreferences.Editor editor = mSettings.edit();
                try {
                    int number = Integer.parseInt(s.toString());
                    editor.putInt("statistics_stock_number", number);
                    editor.commit();
                    BarApplication.getInstance().mStatisticsStockNumber = number;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mDatabaseSqlServerHostEt = (EditText) findViewById(R.id.database_sqlserver_host_et);
        mDatabaseSqlServerHostEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putString("sqlserver_host", s.toString());
                editor.commit();
                BarApplication.getInstance().mSqlServerHost = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mDatabaseSqlServerUserEt = (EditText) findViewById(R.id.database_sqlserver_user_et);
        mDatabaseSqlServerUserEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putString("sqlserver_user", s.toString());
                editor.commit();
                BarApplication.getInstance().mSqlServerUser = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mDatabaseSqlServerPasswordEt = (EditText) findViewById(R.id.database_sqlserver_password_et);
        mDatabaseSqlServerPasswordEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putString("sqlserver_password", s.toString());
                editor.commit();
                BarApplication.getInstance().mSqlServerPassword = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mDatabaseSqlServerDatabaseNameEt = (EditText) findViewById(R.id.database_sqlserver_databasename_et);
        mDatabaseSqlServerDatabaseNameEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SharedPreferences.Editor editor = mSettings.edit();
                editor.putString("sqlserver_databasename", s.toString());
                editor.commit();
                BarApplication.getInstance().mSqlServerDatabaseName = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        mSynchronousSourceDateEt = (EditText)findViewById(R.id.synchronous_source_date_et);
        mSynchronousSourceDateEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                BarApplication.getInstance().mSynchronousSourceSaleDate = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        if (BarApplication.getInstance().mbStockDisplayPicture)
            mDisplayPictureSB.setChecked(true);
        else
            mDisplayPictureSB.setChecked(false);
        if (BarApplication.getInstance().mbStockDisplayCost)
            mDisplayCostSB.setChecked(true);
        else
            mDisplayCostSB.setChecked(false);
        if (BarApplication.getInstance().mbStockDisplayInnerCircle)
            mDisplayInnerCircleSB.setChecked(true);
        else
            mDisplayInnerCircleSB.setChecked(false);
        if (BarApplication.getInstance().mDatabaseIsSqlServer)
            mDatabaseSB.setChecked(true);
        else
            mDatabaseSB.setChecked(false);

        mStoreNameEt.setText(BarApplication.getInstance().mStoreName);
        mDatabaseStatisticsStockNumberEt.setText(String.valueOf(BarApplication.getInstance().mStatisticsStockNumber));
        mDatabaseSqlServerHostEt.setText(BarApplication.getInstance().mSqlServerHost);
        mDatabaseSqlServerUserEt.setText(BarApplication.getInstance().mSqlServerUser);
        mDatabaseSqlServerPasswordEt.setText(BarApplication.getInstance().mSqlServerPassword);
        mDatabaseSqlServerDatabaseNameEt.setText(BarApplication.getInstance().mSqlServerDatabaseName);
        mSynchronousSourceDateEt.setText(BarApplication.getInstance().mSynchronousSourceSaleDate);

        setView(BarApplication.getInstance().mDatabaseIsSqlServer);

        long time = Config.getFastfoodLastSysncTime();
        if (time != -1) {
            TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            sdf.setTimeZone(timeZone);
            String dddddd = sdf.format(new Date(time));
            mFastfoodSynchronousTipsTv.setText("上次同步 " + dddddd);
        }
        time = Config.getIsszmbalv3LastSysncTime();
        if (time != -1) {
            TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            sdf.setTimeZone(timeZone);
            String dddddd = sdf.format(new Date(time));
            mIsszmbalv3SynchronousTipsTv.setText("上次同步 " + dddddd);
        }
    }

    private void setView(boolean isDatabaseSqlServer) {
        if (isDatabaseSqlServer) {
            findViewById(R.id.database_sqlserver_host_rl).setVisibility(View.VISIBLE);
            findViewById(R.id.database_sqlserver_user_rl).setVisibility(View.VISIBLE);
            findViewById(R.id.database_sqlserver_password_rl).setVisibility(View.VISIBLE);
            findViewById(R.id.database_sqlserver_databasename_rl).setVisibility(View.VISIBLE);
            findViewById(R.id.database_fastfood_sqlserver_synchronous_rl).setVisibility(View.GONE);
            findViewById(R.id.database_isszmbalv3_sqlserver_synchronous_rl).setVisibility(View.VISIBLE);
            findViewById(R.id.synchronous_source_date_rl).setVisibility(View.VISIBLE);
            findViewById(R.id.fastfood_member_export_rl).setVisibility(View.GONE);
            findViewById(R.id.isszmbalv3_member_export_rl).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.tv21)).setText("正在使用SQL Server数据库");
        } else {
            findViewById(R.id.database_sqlserver_host_rl).setVisibility(View.GONE);
            findViewById(R.id.database_sqlserver_user_rl).setVisibility(View.GONE);
            findViewById(R.id.database_sqlserver_password_rl).setVisibility(View.GONE);
            findViewById(R.id.database_sqlserver_databasename_rl).setVisibility(View.GONE);
            findViewById(R.id.database_fastfood_sqlserver_synchronous_rl).setVisibility(View.GONE);
            findViewById(R.id.database_isszmbalv3_sqlserver_synchronous_rl).setVisibility(View.GONE);
            findViewById(R.id.synchronous_source_date_rl).setVisibility(View.GONE);
            findViewById(R.id.fastfood_member_export_rl).setVisibility(View.GONE);
            findViewById(R.id.isszmbalv3_member_export_rl).setVisibility(View.GONE);
            ((TextView) findViewById(R.id.tv21)).setText("正在使用本地数据库");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.display_picture_rl:
                break;
            case R.id.display_cost_rl:
                break;
            case R.id.database_sqlserver_rl:
                break;
            case R.id.database_sqlserver_host_rl:
                break;
            case R.id.database_sqlserver_user_rl:
                break;
            case R.id.database_sqlserver_password_rl:
                break;
            case R.id.database_sqlserver_databasename_rl:
                break;
            case R.id.database_fastfood_sqlserver_synchronous_rl:
                synchronousFastfoodDatabaseToLocal();
                break;
            case R.id.database_isszmbalv3_sqlserver_synchronous_rl:
                synchronousIsszmbalv3DatabaseToLocal();
                break;
            case R.id.fastfood_member_export_rl:
                saveFastfoodContact();
                break;
            case R.id.isszmbalv3_member_export_rl:
                saveIsszmbalv3Contact();
                break;
            case R.id.database_local_delete_rl:
                deleteLocalDataBase();
                break;
            case R.id.about_rl:
                Intent intent = new Intent(SettingActivity.this, AboutActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void deleteLocalDataBase() {
        DatabaseManager.deleteAllIsszmbalv3StockInfoFromHistory(SettingActivity.this);
        DatabaseManager.deleteAllIsszmbalv3MemberInfoFromHistory(SettingActivity.this);
        Toast.makeText(SettingActivity.this, "已清空最近修改商品和会员！", Toast.LENGTH_SHORT).show();
    }

    private void synchronousFastfoodDatabaseToLocal() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SettingActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mFastfoodSynchronousTipsTv.setText("正在同步");
                    }
                });

                LocalDatabaseHelper localDatabaseHelper = LocalDatabaseHelper.getInstance(getApplicationContext());
                localDatabaseHelper.deleteAllStocks();
                localDatabaseHelper.deleteAllStockType();
                localDatabaseHelper.deleteAllMember();

                MicrosoftSQLServerHelper sQLServerHelper = MicrosoftSQLServerHelper.getInstance(getApplicationContext());

                try {
                    ContentValues typeInitialValues = new ContentValues();
                    Map<String, String> stockTypeMap = sQLServerHelper.getAllStockType();
                    for (Map.Entry<String, String> entry : stockTypeMap.entrySet()) {
                        typeInitialValues.put(DatabaseManager.STOCK_TYPE_TYPEID, entry.getKey());
                        typeInitialValues.put(DatabaseManager.STOCK_TYPE_TYPENAME, entry.getValue());
                        localDatabaseHelper.insertStockType(typeInitialValues);
                    }

                    ContentValues stockInitialValues = new ContentValues();
                    final List<StockInfo> resultStocks = sQLServerHelper.getAll(0, -1, -1, -1);
                    for (int i = 0; i < resultStocks.size(); i++) {
                        StockInfo stock = resultStocks.get(i);
                        stockInitialValues.put(DatabaseManager.STOCK_STOCKID, stock.stockId);
                        stockInitialValues.put(DatabaseManager.STOCK_STOCKNAME, stock.stockName);
                        stockInitialValues.put(DatabaseManager.STOCK_SPELL, stock.stockSpell);
                        stockInitialValues.put(DatabaseManager.STOCK_TYPEID, stock.stockTpyeId);
                        stockInitialValues.put(DatabaseManager.STOCK_COST, stock.stockCost);
                        stockInitialValues.put(DatabaseManager.STOCK_RETAIL_PRICE, stock.stockDetailPrice);
                        stockInitialValues.put(DatabaseManager.STOCK_MEMBER_PRICE, stock.stockMemberPrice);
                        stockInitialValues.put(DatabaseManager.STOCK_BARCODE, stock.stockBarcode);
                        localDatabaseHelper.insertStock(stockInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mFastfoodSynchronousTipsTv.setText("已同步商品 " + cur + "/" + resultStocks.size());
                            }
                        });
                    }

                    ContentValues memberInitialValues = new ContentValues();
                    final List<Member> resultMembers = sQLServerHelper.getAllMember(0, -1, -1, String.valueOf(0), -1);
                    for (int i = 0; i < resultMembers.size(); i++) {
                        Member member = resultMembers.get(i);
                        memberInitialValues.put(DatabaseManager.MEMBER_MEMBERID, member.memberId);
                        memberInitialValues.put(DatabaseManager.MEMBER_NAME, member.memberName);
                        memberInitialValues.put(DatabaseManager.MEMBER_SEX, member.memberSex);
                        memberInitialValues.put(DatabaseManager.MEMBER_MOBILE, member.memberMobile);
                        memberInitialValues.put(DatabaseManager.MEMBER_POINT, member.memberPoint);
                        memberInitialValues.put(DatabaseManager.MEMBER_MEMBERTYPE, member.memberType);
                        memberInitialValues.put(DatabaseManager.MEMBER_CARDID, member.memberCardid);
                        memberInitialValues.put(DatabaseManager.MEMBER_MODIFY_SN, member.memberModifySn);
                        memberInitialValues.put(DatabaseManager.MEMBER_TOTAL_CONSUME, member.memberTotalConsume);
                        localDatabaseHelper.insertMember(memberInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mFastfoodSynchronousTipsTv.setText("已同步会员 " + cur + "/" + resultMembers.size());
                            }
                        });
                    }

                    ContentValues payMasterInitialValues = new ContentValues();
                    final List<PayMaster> resultPayMaster = sQLServerHelper.getByPayMasterOperdate(BarApplication.mSynchronousSourceSaleDate);
                    for (int i = 0; i < resultPayMaster.size(); i++) {
                        PayMaster payMaster = resultPayMaster.get(i);
                        payMasterInitialValues.put(DatabaseManager.PAY_MASTER_BILLNO, payMaster.payMasterBillno);
                        payMasterInitialValues.put(DatabaseManager.PAY_MASTER_OPERDATE, payMaster.payMasterOperdate + " " + payMaster.payMasterOpertime);
                        payMasterInitialValues.put(DatabaseManager.PAY_MASTER_BLOTOUT, payMaster.payMasterBlotout);
                        payMasterInitialValues.put(DatabaseManager.PAY_MASTER_TOTAL, payMaster.payMasterTotal);
                        payMasterInitialValues.put(DatabaseManager.PAY_MASTER_RECEIVABLE, payMaster.payMasterReceivable);
                        localDatabaseHelper.insertPayMaster(payMasterInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mFastfoodSynchronousTipsTv.setText("已同步销售额列表 " + cur + "/" + resultPayMaster.size());
                            }
                        });
                    }

                    ContentValues saleDetailInitialValues = new ContentValues();
                    final List<SaleDetailInfo> resultSaleDetail = sQLServerHelper.getSaleDetailByDate(BarApplication.mSynchronousSourceSaleDate);
                    for (int i = 0; i < resultSaleDetail.size(); i++) {
                        SaleDetailInfo saleDetailInfo = resultSaleDetail.get(i);
                        saleDetailInitialValues.put(DatabaseManager.SALE_DETAIL_BILLNO, saleDetailInfo.saleDetailBillno);
                        saleDetailInitialValues.put(DatabaseManager.SALE_DETAIL_STOCKID, saleDetailInfo.saleDetailStockid);
                        saleDetailInitialValues.put(DatabaseManager.SALE_DETAIL_QUANTITY, saleDetailInfo.saleDetailQuantity);
                        saleDetailInitialValues.put(DatabaseManager.SALE_DETAIL_OPERATEDATE, saleDetailInfo.saleDetailOperdate + " " + saleDetailInfo.saleDetailOpertime);
                        saleDetailInitialValues.put(DatabaseManager.SALE_DETAIL_PRICE, saleDetailInfo.saleDetailPrice);
                        saleDetailInitialValues.put(DatabaseManager.SALE_DETAIL_COST, saleDetailInfo.saleDetailCost);
                        saleDetailInitialValues.put(DatabaseManager.SALE_DETAIL_PRICE_ORIG, 0);
                        localDatabaseHelper.insertSaleDetail(saleDetailInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mFastfoodSynchronousTipsTv.setText("已同步销售详情 " + cur + "/" + resultSaleDetail.size());
                            }
                        });
                    }

                    SettingActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            long timeNow = System.currentTimeMillis();
                            Config.setFastfoodLastSysncTime(timeNow);
                            if (timeNow != -1) {
                                TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                sdf.setTimeZone(timeZone);
                                String dddddd = sdf.format(new Date(timeNow));
                                mFastfoodSynchronousTipsTv.setText("同步结束 " + dddddd);
                            }
                        }
                    });

                } catch (final Exception e) {
                    SettingActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mFastfoodSynchronousTipsTv.setText(e.toString());
                        }
                    });
                }
            }
        }).start();
    }

    private void synchronousIsszmbalv3DatabaseToLocal() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SettingActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mIsszmbalv3SynchronousTipsTv.setText("正在同步");
                    }
                });

                LocalDatabaseHelper localDatabaseHelper = LocalDatabaseHelper.getInstance(getApplicationContext());
                localDatabaseHelper.deleteAllIsszmbalv3Stocks();
                localDatabaseHelper.deleteAllIsszmbalv3StockType();
                localDatabaseHelper.deleteAllIsszmbalv3Member();
                localDatabaseHelper.deleteAllIsszmbalv3Branch();
                localDatabaseHelper.deleteAllIsszmbalv3Supcust();
                localDatabaseHelper.deleteAllIsszmbalv3PayFlow();
                localDatabaseHelper.deleteAllIsszmbalv3SaleDetail();

                MicrosoftSQLServerHelper sQLServerHelper = MicrosoftSQLServerHelper.getInstance(getApplicationContext());

                try {
                    ContentValues typeInitialValues = new ContentValues();
                    Map<String, String> isszmbalv3StockTypeMap = sQLServerHelper.getIsszmbalv3AllStockType();
                    for (Map.Entry<String, String> entry : isszmbalv3StockTypeMap.entrySet()) {
                        typeInitialValues.put(DatabaseManager.ISSZMBALV3_ITEM_CLS_ITEM_CLSNO, entry.getKey());
                        typeInitialValues.put(DatabaseManager.ISSZMBALV3_ITEM_CLS_ITEM_CLSNAME, entry.getValue());
                        localDatabaseHelper.insertIsszmbalv3StockType(typeInitialValues);
                    }

                    ContentValues stockInitialValues = new ContentValues();
                    final List<Isszmbalv3StockInfo> resultIsszmbalv3Stocks = sQLServerHelper.getAllIsszmbalv3Stock(0, -1, -1, -1);
                    for (int i = 0; i < resultIsszmbalv3Stocks.size(); i++) {
                        Isszmbalv3StockInfo isszmbalv3stock = resultIsszmbalv3Stocks.get(i);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_no, isszmbalv3stock.item_no);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_name, isszmbalv3stock.item_name);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_subname, isszmbalv3stock.item_subname);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_info_item_clsno, isszmbalv3stock.item_clsno);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_item_rem, isszmbalv3stock.item_rem);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_price, isszmbalv3stock.price);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_sale_price, isszmbalv3stock.sale_price);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_measure_flag, isszmbalv3stock.measure_flag);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_new_oper_id, isszmbalv3stock.new_oper_id);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_modify_oper_id, isszmbalv3stock.modify_oper_id);
                        stockInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_item_vip_acc_flag, isszmbalv3stock.vip_acc_flag);
                        localDatabaseHelper.insertIsszmbalv3Stock(stockInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIsszmbalv3SynchronousTipsTv.setText("已同步商品 " + cur + "/" + resultIsszmbalv3Stocks.size());
                            }
                        });
                    }

                    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    ContentValues isszmbalv3MemberInitialValues = new ContentValues();
                    final List<Isszmbalv3Member> resultIsszmbalv3Members = sQLServerHelper.getAllIsszmbalv3Member(0, -1, -1, String.valueOf(0), -1);
                    for (int i = 0; i < resultIsszmbalv3Members.size(); i++) {
                        Isszmbalv3Member isszmbalv3Member = resultIsszmbalv3Members.get(i);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_card_type, isszmbalv3Member.memberCardType);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_card_id, isszmbalv3Member.memberCardId);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_card_no, isszmbalv3Member.memberCardNo);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_name, isszmbalv3Member.memberName);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_sex, isszmbalv3Member.memberSex);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_tel, isszmbalv3Member.memberTel);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_email, isszmbalv3Member.memberEmail);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_mobile, isszmbalv3Member.memberMobile);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_consum_count, isszmbalv3Member.memberConsumCount);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_consum_amt, isszmbalv3Member.memberConsumAmt);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_acc_num, isszmbalv3Member.memberAccNum);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_dec_num, isszmbalv3Member.memberDecNum);
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_start_date, dateformat.format(isszmbalv3Member.memberVipStartDay));
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_end_date, dateformat.format(isszmbalv3Member.memberVipEndDay));
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_sav_start_date, dateformat.format(isszmbalv3Member.memberSavStartDay));
                        isszmbalv3MemberInitialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_sav_end_date, dateformat.format(isszmbalv3Member.memberSavEndDay));
                        localDatabaseHelper.insertIsszmbalv3Member(isszmbalv3MemberInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIsszmbalv3SynchronousTipsTv.setText("已同步会员 " + cur + "/" + resultIsszmbalv3Members.size());
                            }
                        });
                    }

                    ContentValues branchInitialValues = new ContentValues();
                    final List<Isszmbalv3BranchInfo> resultIsszmbalv3BranchInfo = sQLServerHelper.getIsszmbalv3BranchInfo();
                    for (int i = 0; i < resultIsszmbalv3BranchInfo.size(); i++) {
                        Isszmbalv3BranchInfo isszmbalv3BranchInfo = resultIsszmbalv3BranchInfo.get(i);
                        branchInitialValues.put(DatabaseManager.ISSZMBALV3_BRANCH_INFO_BRANCH_NO, isszmbalv3BranchInfo.no);
                        branchInitialValues.put(DatabaseManager.ISSZMBALV3_BRANCH_INFO_BRANCH_NAME, isszmbalv3BranchInfo.name);
                        branchInitialValues.put(DatabaseManager.ISSZMBALV3_BRANCH_INFO_PROPERTY, isszmbalv3BranchInfo.property);
                        localDatabaseHelper.insertIsszmbalv3BranchInfo(branchInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIsszmbalv3SynchronousTipsTv.setText("已同步门店列表 " + cur + "/" + resultIsszmbalv3BranchInfo.size());
                            }
                        });
                    }

                    ContentValues supcustInitialValues = new ContentValues();
                    final List<Isszmbalv3SupcustInfo> resultIsszmbalv3SupcustInfo = sQLServerHelper.getIsszmbalv3SupcustInfoList();
                    for (int i = 0; i < resultIsszmbalv3SupcustInfo.size(); i++) {
                        Isszmbalv3SupcustInfo isszmbalv3SupcustInfo = resultIsszmbalv3SupcustInfo.get(i);
                        supcustInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_supcust_no, isszmbalv3SupcustInfo.supcust_no);
                        supcustInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_sup_name, isszmbalv3SupcustInfo.sup_name);
                        supcustInitialValues.put(DatabaseManager.ISSZMBALV3_t_bd_supcust_info_sup_type, isszmbalv3SupcustInfo.sup_type);
                        localDatabaseHelper.insertIsszmbalv3SupcustInfo(supcustInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIsszmbalv3SynchronousTipsTv.setText("已同步供应商列表 " + cur + "/" + resultIsszmbalv3SupcustInfo.size());
                            }
                        });
                    }

                    ContentValues payFlowInitialValues = new ContentValues();
                    final List<Isszmbalv3PayFlow> resultIsszmbalv3PayFlow = sQLServerHelper.getIsszmbalv3PayFlowByOperdate(BarApplication.mSynchronousSourceSaleDate,"");
                    for (int i = 0; i < resultIsszmbalv3PayFlow.size(); i++) {
                        Isszmbalv3PayFlow isszmbalv3PayFlow = resultIsszmbalv3PayFlow.get(i);
                        payFlowInitialValues.put(DatabaseManager.ISSZMBALV3_PAY_FLOW_FLOW_NO, isszmbalv3PayFlow.payFlowFlow_no);
                        payFlowInitialValues.put(DatabaseManager.ISSZMBALV3_BRANCH_INFO_BRANCH_NO, isszmbalv3PayFlow.payFlowBranch_no);
                        payFlowInitialValues.put(DatabaseManager.ISSZMBALV3_PAY_FLOW_OPERDATE, isszmbalv3PayFlow.payFlowOperdate + " " + isszmbalv3PayFlow.payFlowOpertime);
                        payFlowInitialValues.put(DatabaseManager.ISSZMBALV3_PAY_FLOW_SALE_AMOUNT, isszmbalv3PayFlow.payFlowSale_amount);
                        payFlowInitialValues.put(DatabaseManager.ISSZMBALV3_PAY_FLOW_PAY_AMOUNT, isszmbalv3PayFlow.payFlowPay_amount);
                        payFlowInitialValues.put(DatabaseManager.ISSZMBALV3_PAY_FLOW_PAY_WAY, isszmbalv3PayFlow.payFlowPay_way);
                        localDatabaseHelper.insertIsszmbalv3PayFlow(payFlowInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIsszmbalv3SynchronousTipsTv.setText("已同步销售额列表 " + cur + "/" + resultIsszmbalv3PayFlow.size());
                            }
                        });
                    }

                    ContentValues isszmbalv3SaleDetailInitialValues = new ContentValues();
                    final List<Isszmbalv3SaleDetailInfo> resultIsszmbalv3SaleDetailInfo = sQLServerHelper.getIsszmbalv3SaleDetailByDate(BarApplication.mSynchronousSourceSaleDate,"");
                    for (int i = 0; i < resultIsszmbalv3SaleDetailInfo.size(); i++) {
                        Isszmbalv3SaleDetailInfo isszmbalv3SaleDetailInfo = resultIsszmbalv3SaleDetailInfo.get(i);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_SALE_FLOW_FLOW_NO, isszmbalv3SaleDetailInfo.saleDetailflow_no);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_BRANCH_INFO_BRANCH_NO, isszmbalv3SaleDetailInfo.saleDetailbranch_no);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_SALE_FLOW_ITEM_NO, isszmbalv3SaleDetailInfo.saleDetailitem_no);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_SALE_FLOW_SOURCE_PRICE, isszmbalv3SaleDetailInfo.saleDetailPrice);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_SALE_FLOW_OPERDATE, isszmbalv3SaleDetailInfo.saleDetailOperdate + " " + isszmbalv3SaleDetailInfo.saleDetailOpertime);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_SALE_FLOW_COST_PRICE, isszmbalv3SaleDetailInfo.saleDetailCost);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_SALE_FLOW_SALE_QNTY, isszmbalv3SaleDetailInfo.saleDetailQuantity);
                        isszmbalv3SaleDetailInitialValues.put(DatabaseManager.ISSZMBALV3_SALE_FLOW_SALE_MONER, isszmbalv3SaleDetailInfo.saleDetailSaleMonery);
                        localDatabaseHelper.insertIsszmbalv3SaleDetail(isszmbalv3SaleDetailInitialValues);
                        final int cur = i;
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIsszmbalv3SynchronousTipsTv.setText("已同步销售详情 " + cur + "/" + resultIsszmbalv3SaleDetailInfo.size());
                            }
                        });
                    }

                    SettingActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            long timeNow = System.currentTimeMillis();
                            Config.setIsszmbalv3LastSysncTime(timeNow);
                            if (timeNow != -1) {
                                TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                sdf.setTimeZone(timeZone);
                                String dddddd = sdf.format(new Date(timeNow));
                                mIsszmbalv3SynchronousTipsTv.setText("同步结束 " + dddddd);
                            }
                        }
                    });

                } catch (final Exception e) {
                    SettingActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mIsszmbalv3SynchronousTipsTv.setText(e.toString());
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * @desc 导出Fastfood联系人
     * @author taoli
     * @time 2017/7/26 0026
     */
    private void saveFastfoodContact() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SettingActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mFastfoodMemberExportTipsTv.setText("正在导出Fastfood联系人");
                    }
                });

                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    try {
                        File file = new File(Environment.getExternalStorageDirectory(), "FastfoodContacts.vcf");
                        MicrosoftSQLServerHelper sQLServerHelper = MicrosoftSQLServerHelper.getInstance(getApplicationContext());
                        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                        VCardComposer composer = new VCardComposer();
                        final List<Member> resultMember = sQLServerHelper.getAllMember(0, -1, -1, String.valueOf(0), -1);
                        for (int i = 0; i < resultMember.size(); i++) {
                            Member member = resultMember.get(i);
                            if (TextUtils.isEmpty(member.memberMobile))
                                continue;
                            ContactStruct contact = new ContactStruct();
                            contact.name = member.memberMobile;
                            contact.addPhone(Contacts.Phones.TYPE_MOBILE, member.memberMobile, null, true);
                            String vcardString = composer.createVCard(contact, VCardComposer.VERSION_VCARD30_INT);
                            writer.write(vcardString);
                            final int cur = i;
                            SettingActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mFastfoodMemberExportTipsTv.setText("已导出会员 " + cur + "/" + resultMember.size());
                                }
                            });
                        }
                        writer.close();
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String path = Environment.getExternalStorageDirectory().getPath() + "/FastfoodContacts.vcf";
                                mFastfoodMemberExportTipsTv.setText("导出路径 " + path);
                            }
                        });

                    } catch (final Exception e) {
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mFastfoodMemberExportTipsTv.setText(e.toString());
                            }
                        });
                    }
                }
            }
        }).start();
    }

    /**
     * @desc 导出思迅联系人
     * @author taoli
     * @time 2017/7/26 0026
     */
    private void saveIsszmbalv3Contact() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SettingActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mIsszmbalv3MemberExportTipsTv.setText("正在导出思迅联系人");
                    }
                });

                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    try {
                        File file = new File(Environment.getExternalStorageDirectory(), "Isszmbalv3Contacts.vcf");
                        MicrosoftSQLServerHelper sQLServerHelper = MicrosoftSQLServerHelper.getInstance(getApplicationContext());
                        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                        VCardComposer composer = new VCardComposer();
                        final List<Isszmbalv3Member> resultIsszmbalv3Member = sQLServerHelper.getAllIsszmbalv3Member(0, -1, -1, String.valueOf(0), -1);
                        for (int i = 0; i < resultIsszmbalv3Member.size(); i++) {
                            Isszmbalv3Member isszmbalv3Member = resultIsszmbalv3Member.get(i);
                            String mobile = null;
                            if ( !TextUtils.isEmpty(isszmbalv3Member.memberTel) ){
                                mobile = isszmbalv3Member.memberTel.trim();
                            }else if(!TextUtils.isEmpty(isszmbalv3Member.memberMobile)){
                                mobile = isszmbalv3Member.memberMobile.trim();
                            }
                            if( TextUtils.isEmpty(mobile))
                                return;
                            ContactStruct contact = new ContactStruct();
                            contact.name = mobile;
                            contact.addPhone(Contacts.Phones.TYPE_MOBILE, mobile, null, true);
                            String vcardString = composer.createVCard(contact, VCardComposer.VERSION_VCARD30_INT);
                            writer.write(vcardString);
                            final int cur = i;
                            SettingActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mIsszmbalv3MemberExportTipsTv.setText("已导出会员 " + cur + "/" + resultIsszmbalv3Member.size());
                                }
                            });
                        }
                        writer.close();
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String path = Environment.getExternalStorageDirectory().getPath() + "/Isszmbalv3Contacts.vcf";
                                mIsszmbalv3MemberExportTipsTv.setText("导出路径 " + path);
                            }
                        });

                    } catch (final Exception e) {
                        SettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIsszmbalv3MemberExportTipsTv.setText(e.toString());
                            }
                        });
                    }
                }
            }
        }).start();
    }
}
